package com.simon.nearbyfootball.app;

import java.io.File;
import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.simon.nearbyfootball.misc.JsonUtil;

import android.content.Context;

public class AppConfig {
	private Config m_config = new Config();
	private ObjectMapper m_object_mapper;
	private final static String APP_CONFIG = "config";
	private static AppConfig INSTANCE = null; 
	
	
	public static class Config{
		private String _city = "";
		
		
		public void setCity(String city){
			_city = city;
		}
		
		
		public String getCity(){
			return _city;
		}
	}
	
	public static AppConfig getInstance(){
		if(INSTANCE == null){
			INSTANCE = new AppConfig();
		}
		
		return INSTANCE;
	}
	
	private AppConfig(){
		m_object_mapper = JsonUtil.getObjectMapper();
	}
	
	
	private Config _load(Context context){
		Config config = new Config();
		File dirConf = context.getDir(APP_CONFIG, Context.MODE_PRIVATE);
		File conf = new File(dirConf, APP_CONFIG);
		
		try {
			config = m_object_mapper.readValue(conf, Config.class);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			conf.delete();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			conf.delete();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return config;
	}
	
	
	public void load(Context context){
		m_config = _load(context);
	}
	
	
	public void save(Context context){
		File dirConf = context.getDir(APP_CONFIG, Context.MODE_PRIVATE);
		File conf = new File(dirConf, APP_CONFIG);
		try {
			m_object_mapper.writeValue(conf, m_config);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public void setCity(String city){
		m_config.setCity(city);
		save(AppContext.getAppContext());
	}
	
	public String getCity(){
		return m_config.getCity();
	}
	
}
